using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[CreateAssetMenu(fileName = "New Quest",menuName = "Quest/QuestData")]
public class QuestData_SO : ScriptableObject
{
   [Serializable]
   public class QuestRequire
   {
      public string requiretName;
      public int requireAmount;
      public int currentAmount;
   }
   public string questName;

   [TextArea] 
   public string description;

   public bool isStarted;
   public bool isComplete;
   public bool isFinished;

   
   public List<QuestRequire> questRequires = new List<QuestRequire>();
   public List<InventoryItem> rewardItems = new List<InventoryItem>();

   public void GiveRewards()
   {
      foreach (var reward in rewardItems)
      {
         if (reward.amount < 0)
         {
            int requireCount = Mathf.Abs(reward.amount);
            if (InventoryManager.Instance.QuestItemInBag(reward.itemData) != null)
            {
               if (InventoryManager.Instance.QuestItemInBag(reward.itemData).amount >= requireCount)
               {
                  InventoryManager.Instance.QuestItemInBag(reward.itemData).amount -= requireCount;
               }
               else if (InventoryManager.Instance.QuestItemInBag(reward.itemData).amount < requireCount)
               {
                  requireCount -= InventoryManager.Instance.QuestItemInBag(reward.itemData).amount;
                  InventoryManager.Instance.QuestItemInBag(reward.itemData).amount = 0;
                  if (InventoryManager.Instance.QuestItemInAction(reward.itemData) != null)
                  {
                     InventoryManager.Instance.QuestItemInAction(reward.itemData).amount -= requireCount;
                  }
               }
            }
            else
            {
               InventoryManager.Instance.QuestItemInAction(reward.itemData).amount -= requireCount;
            }
         }
         else
         {
            InventoryManager.Instance.bagData.AddItem(reward.itemData,reward.amount);
         }
         InventoryManager.Instance.bagUI.RefreshUI();
         InventoryManager.Instance.actionUI.RefreshUI();
      }
   }

   public void CheackQuestProgress()
   {
      var finishedRequires = questRequires.Where(r => r.requireAmount <= r.currentAmount);
      isComplete = finishedRequires.Count() == questRequires.Count;
   }

   public List<string> RequireTargetName()
   {
      List<string> questNameList = new List<string>();
      foreach (var require in questRequires)
      {
         questNameList.Add(require.requiretName);
      }

      return questNameList;
   }
}
